﻿function body_onload() 
{        
    var answers = new Array();

    loadQuestionsFromService();
    loadAnswersFromService();
}

function CreateAnswerDiv(questionId, answerId, answerContent)
{ 
    var radio = $('<input />');
    radio.attr('type', 'radio');
    radio.attr('id', 'answerId_' + answerId);
    radio.attr('name', 'questionId_' + questionId);
    radio.attr('questionId', questionId);
    radio.attr('value', answerId);
    radio.attr('answerId', answerId);
    radio.click(radioButtonAnswer_onclick);
    
    var label = $('<label>' + answerContent +'</label>');
    label.attr('for', radio.attr('id'));    

    var div = $('<div></div>');
    div.attr('class', 'answer');
    div.append(radio);
    div.append(label); 
    
    return div;
}

function radioButtonAnswer_onclick(event)
{
    if(document.event)
    {
        event = document.event;
    }

    var radioButton = $('#' + event.target.id);
    questionsToAnswers[radioButton.attr('questionId')] = radioButton.attr('answerId');
}



function CreateButtonVote(questionId)
{
    var button = $('<input />');
    button.attr('type', 'button');
    button.attr('id', 'buttonVoteFor_' + questionId);
    button.attr('class', 'coolButton');
    button.attr('value', 'Vote');
    button.attr('questionId', questionId);

    button.click(buttonVoteFor_onclick);

    return button;
}

function buttonVoteFor_onclick(event) 
{    
    if(document.event)
    {
        event = document.event;
    }

    var buttonVotefor = $('#' + event.target.id);
    
    var questionId = buttonVotefor.attr('questionId');

    if(!questionsToAnswers[questionId])
    {
        alert('You have not answered the question.');
        return;
    }
    
    lastAnsweredQuestionId = questionId;    

    var answerId = questionsToAnswers[questionId];

    var serviceUrl = "http://" + document.location.host + "/PollSystemService.svc/VoteForAnswerAndGetVotesCount/" + answerId;

    $.ajax({
        async: true,
        type: "POST",
        url: serviceUrl,
        contentType: "application/json;charset=utf-8",
        success: onVote_Success,
        error: function () 
        {
            alert('Voting failed. Please try again later.');
        }
    });        
}

function onVote_Success(data)
{    
    $('.questions > *').remove();            
    onResultsLoaded_Success(data);    
}

function onResultsLoaded_Success(data) {

    if(data.length != 0)
    {
        var newAnswers = data;

        var questionId = data[0].QuestionId;

        for (var i = 0; i < answers.length; i++) 
        {
            if(answers[i].QuestionId == questionId)
            {
                answers.splice(i, 1);
                i--;
            }
        }

        for (var i = 0; i < newAnswers.length; i++) 
        {
            answers.push(newAnswers[i]);
        }

        CreateResultsDiv(lastAnsweredQuestionId);
    }    
}

function CreateResultsDiv(questionId)
{    
    var div = $('<div></div>');
    div.attr('class', 'results');    
    
    var questionContent =  GetQuestionContentByQuestionId(questionId);
    div.append(questionContent);
    
    var totalVotes = CountTotalVotes(questionId);

    var table = $('<table></table');    
    
    for (var i = 0; i < answers.length; i++) 
    {
        if(answers[i].QuestionId == questionId)
        {   
            var tr = $('<tr></tr>');

            var td1 = $('<td></td>');
            td1.html(answers[i].AnswerContent);
                             
            var votesPercentageFloat =  parseFloat(answers[i].VotesCount) /  parseFloat(totalVotes);
            var votesPercentageInt = parseInt(100 * votesPercentageFloat);               
            var votesPercentage = votesPercentageInt + '%';

            var percentageDiv = $('<div></div>');
            percentageDiv.append(votesPercentage);
            percentageDiv.css('width', votesPercentage);
            percentageDiv.attr('class', 'resultPercentage');

            var td2 = $('<td></td>');
            td2.html(percentageDiv);            

            tr.append(td1);
            tr.append(td2);

            table.append(tr);
        }
    }

    div.append(table);

    var buttonBack = $('<input />');
    buttonBack.attr('value', "Back to Polls");
    buttonBack.attr('class', 'coolButton');
    buttonBack.attr('type', 'button');    
    buttonBack.click(buttonBackToPolls_onclick);

    div.append(buttonBack);

    $('#results').append(div);    
}

function buttonBackToPolls_onclick(event) 
{    
    answers = null;
    questions = null;
    lastAnsweredQuestionId = null;
    questionsToAnswers = new Array(); 

    $('#results > *').remove();

    loadQuestionsFromService();
    loadAnswersFromService();    
}

function CountTotalVotes(questionId)
{
    var count = 0;

    for (var i = 0; i < answers.length; i++) 
    {
        if(answers[i].QuestionId == questionId)
        {
            count += answers[i].VotesCount;
        }
    }

    return count;
}

function GetQuestionContentByQuestionId(questionId)
{
    for (var i = 0; i < questions.length; i++) 
    {
        if(questions[i].QuestionId == questionId)
        {
            return questions[i].QuestionContent
        }
    }

    return 'error, questionId not found';
}

function CreateQuestionAndAnswersDiv(questionId, questionContent, answers)
{
    var div = $('<div></div>');
    div.attr('class', 'questionAndAnswers');
    div.append(questionContent);

    for (var i = 0; i < answers.length; i++) 
    {
        var answerDiv = CreateAnswerDiv(questionId, answers[i].AnswerId, answers[i].AnswerContent);
        div.append(answerDiv);
    }

    var button = CreateButtonVote(questionId);
    div.append(button);

    return div;
}

var lastAnsweredQuestionId;
var questions;
var answers;
var answersByQuestionId;
var questionsToAnswers = new Array();

function loadQuestionsFromService() {
    
    var serviceUrl = "http://" + document.location.host + "/PollSystemService.svc/Questions";     

    $.ajax(
    {
        async: true,
        type: "GET",
        url: serviceUrl,
        contentType: "application/json;charset=utf-8",
        success: onLoadQuestionsFromService_Success,
        error: function () 
        {
            alert('Loading questions failed. Please try again later.');
        }
    });    
}

function onLoadQuestionsFromService_Success(data)
{
    questions = data;
    
    if(answers)
    {
        onQuestionsAndAnswersLoaded();
    }
}


function loadAnswersFromService() {
    
    var serviceUrl = "http://" + document.location.host + "/PollSystemService.svc/Answers";     

    $.ajax(
    {
        async: true,
        type: "GET",
        url: serviceUrl,
        contentType: "application/json;charset=utf-8",
        success: onLoadAnswersFromService_Success,
        error: function () 
        {
            alert('Loading answers failed. Please try again later.');
        }
    });    
}

function onLoadAnswersFromService_Success(data)
{
    answers = data;

    answersByQuestionId = new Array();

    for (var i = 0; i < answers.length; i++) 
    {
        if(!answersByQuestionId[answers[i].QuestionId])
        {            
            answersByQuestionId[answers[i].QuestionId] = new Array();
        }   
        
        answersByQuestionId[answers[i].QuestionId].push(answers[i]);                     
    }    

    if(questions)
    {
        onQuestionsAndAnswersLoaded();
    }
}

function onQuestionsAndAnswersLoaded()
{    
    $('.questions > *').remove();

    var questionAndAnswersDivs = new Array();

    for (var i = 0; i < questions.length; i++) 
    {                
        var answers = answersByQuestionId[questions[i].QuestionId];
        if(!answers)
        {
            //answers = new Array(); // question has no answers 
            continue;
        }            

        questionAndAnswersDivs.push(CreateQuestionAndAnswersDiv(questions[i].QuestionId, questions[i].QuestionContent, answers));     
    }    

    for (var r = 0; r <= questionAndAnswersDivs.length / 3; r++) 
    {
        var row = $('<div></div');
        row.attr('class', 'questionAndAnswersRow');

        for (var i = 0; i < 3; i++) 
        {
            var index = r * 3 + i;            

            if(index >= questionAndAnswersDivs.length)
            {
                break;
            }

            row.append(questionAndAnswersDivs[index]);            
        }             
             
        var clearerDiv = $('<div></div>');
        clearerDiv.attr('class', 'clearer');   
        row.append(clearerDiv);
        
        $('.questions').append(row);
    }    
}

function GenerateId() 
{
	var id ;

	while(true)
	{
		id = GenerateRandomString(10);		
	
		if(document.getElementById(id) == null)
		{			
			break;		
		}		
	}

	return id;
}

function GenerateRandomString(string_length) 
{
	var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";

	var randomstring = '';
	for (var i=0; i < string_length; i++) 
	{
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum, rnum + 1);
	}

	return randomstring;
}

